<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Project as RepositoriesProject;
use App\Http\Controllers\Controller;
use App\Models\ContractTemplate;
use App\Models\Project;
use App\Models\ProjectAgreement;
use App\Models\User;
use App\Services\TimeService;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Traits\HasFormResponse;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Widgets\Tooltip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpWord\TemplateProcessor;
use zgldh\QiniuStorage\QiniuStorage;

class DownloadController extends Controller
{

    use HasFormResponse;

    public function test(Request $request)
    {

        return $this->response()->error('asdf');
    }

    public function index(Content $content)
    {
        $request = \request();

        switch ($request->input('cmd')) {
            case 'agreement': // 协议下载
           
                $agreementModel = ProjectAgreement::where('id', $request->input('agreement_id'))->first();
                if (empty($agreementModel) || empty($agreementModel->agreement_file)) {
                    // 项目
                    $project = Project::where('id', $agreementModel->project_id)->first();
                    // 项目协议
                    $tplModel = ContractTemplate::where('id', $project->tpl_id)->first();
                    $user = User::find($agreementModel->user_id);
                    // dd(storage_path('app/public/') . $tplModel->url);
                    // if ($path = downloadFile($tplModel->url)) { //TemplateProcessor
                    $path  = storage_path('app/public/') . $tplModel->url;
                    if ($path) {
                        // $template = new TemplateProcessor(app()->basePath() . DIRECTORY_SEPARATOR . $path);
                        $template = new TemplateProcessor($path);

                        $datetime = TimeService::formatTimeToString($agreementModel['active_date']);
                        
                        $beforeAfterTax = RepositoriesProject::getBefoeAfterTax();
                        $role = RepositoriesProject::getFeeTypeOptions();
                        // todo 套入协议模板数据
                        $template->setValues([
                            'user_auth_name' => $agreementModel['user_auth_name'],
                            'active_date' => $datetime,
                            'active_week' => $agreementModel['active_week'],
                            'active_time_begin' => isset($agreementModel['active_time_begin']) && !empty($agreementModel['active_time_begin']) ? $agreementModel['active_time_begin'] : '',
                            // 'active_time_end' => $this->agreement['active_time_end'],
                            'active_time_end' => isset($agreementModel['active_time_begin']) && !empty($agreementModel['active_time_begin']) ? $agreementModel['active_time_begin'] : '',
                            'active_name' => $project['active_name'],
                            'role' =>  isset($role[$agreementModel['role']]) ? $role[$agreementModel['role']] : '',
                            'before_after_tax' => isset($beforeAfterTax[$agreementModel['before_after_tax']]) ? $beforeAfterTax[$agreementModel['before_after_tax']] : '',
                            'sponsor' => $project['sponsor'],
                            'fee_type_value' => $agreementModel['fee_type_value'],
                            'fee_type_key' => $user['fee_type_name'],
                            'company' => $project['company'],
                            'company_short' => $project['company_short'],
                            'bank_card' => $agreementModel['bank_card'],
                            'bank_addr' => $agreementModel['bank_addr'],
                            'bank_name' => $agreementModel['bank_name'],
                            'id_number' => $user['id_number'],
                            'phone' => $user['phone'],
                            'unit' => $user['unit'],
                            'agreement_code' => $agreementModel['agreement_code'],
                        ]);

                        $pathinfo = pathinfo($path);
                        $newFile = $pathinfo['dirname'] . DIRECTORY_SEPARATOR . 'new-' . $agreementModel['user_auth_name'] . '-' . $agreementModel['active_date'] . '-' . uniqid() . '-' . $pathinfo['basename'];

                        $template->saveAs($newFile);
                        Log::info('-------生成新的协议文件-------', ['newFile' => $newFile]);
                        $filePath = 'uploads/agreement/' . date('Ymd') . '/' . $agreementModel['user_auth_name'] . '-' . $agreementModel['active_date'] . '-' . uniqid() . '-' . $pathinfo['basename']; //文件路径

                        $res = QiniuStorage::disk('qiniu')->put($filePath, file_get_contents($newFile));
                        Log::info('-------上传七牛云返回结果-------', ['qiniuyun-result' => json_encode($res)]);
                        $agreement_file = '';
                        if ($res) {
                            $obj = QiniuStorage::disk('qiniu')->downloadUrl($filePath);
                            $agreement_file = $obj->getUrl();
                            Log::info('-------获取七牛云的协议地址-------', ['qiniuyun-result' => json_encode($agreement_file)]);
                        }
                        $agreementModel->agreement_file = httpToHttps($agreement_file);
                        $agreementModel->save();
                        Log::info('----------生成协议调度任务结束了----------');
                        // unlink($path);
                        unlink($newFile);
                    }

                    exit('<script> Dcat.error("请稍后, 协议文件生成中", null, {timeOut: 5000}); history.go(-1);</script>');
                }
                exit('<script>window.open("' . $agreementModel->agreement_file . '", "_blank", "noreferrer"); history.go(-1);</script>');
                break;

            case 'export-agreement': // 导出协议
                $path = $request->input('filePath');
                if (!file_exists($path)) {
                    return responses()->setContent('文件不存在');
                }
                return response()->download($path)->deleteFileAfterSend(true);
                break;
            default:
                $alert = Alert::make('未识别的下载');
                $alert->danger();
                return $alert;
                break;
        }
    }
}
